﻿package edzis.translatebuddy.view.components {
	import edzis.translatebuddy.events.DataProxyEvent;
	import edzis.translatebuddy.model.vo.SearchProfileVO;
	import edzis.translatebuddy.model.vo.WordVO;
	import fl.data.DataProvider;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	
	/**
	 * The View Component for adding renaming and deleting search profiles
	 * @author Edgars Simsons
	 */
	public class ManageSearchProfiles extends ManageSearchProfiles_design {
		private var _enterDown	:Boolean;
		
		public function ManageSearchProfiles() {
			visible = false;
		//	wordTxt.autoFillEnabled = true;
		}
		
		public function init(allSearchProfiles:DataProvider) :void {
			ArthropodDebug.log("init");
			urlTxt.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			urlTxt.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			addBtn.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			addBtn.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			addBtn.addEventListener(MouseEvent.CLICK, onAddSearchProfile);
		}
		
		private function onAddSearchProfile(e:MouseEvent):void {
		//	ArthropodDebug.log("wordTxt.selectedLabel" + wordTxt.selectedLabel);
			if (titleTxt.text != "" && urlTxt.text != "") {
				ArthropodDebug.log("onAddSearchProfile " + titleTxt.text);
				var url:String = urlTxt.text;
				
				var protocolValid:Boolean = false;
				if (url.substr(0, 8) != "https://") protocolValid = true;
				else if (url.substr(0, 7) != "http://") protocolValid = true;
				else protocolValid = false;
				
				if (protocolValid) url = "http://" + url;
				
				if (url.match(/#PHRASE#/)) {
					var profile:SearchProfileVO = new SearchProfileVO( titleTxt.text, url );
					dispatchEvent( new DataProxyEvent(DataProxyEvent.ADD_SEARCH_PROFILE, profile));
					titleTxt.text = "";
					urlTxt.text = "";
					stage.focus = titleTxt;
				} else {
					urlTxt.text = url;
				}
				
				
			}
		}
		
		private function onKeyDown(e:KeyboardEvent):void {
			if (e.keyCode == Keyboard.ENTER && !_enterDown) {
				_enterDown = true;
				onAddSearchProfile(null);
			}
		}
		
		private function onKeyUp(e:KeyboardEvent):void {
			if (e.keyCode == Keyboard.ENTER) _enterDown = false;
		}
		
		private function onWordUpdate(e:Event):void{
		}
		
		private function onTranslationUpdate(e:Event):void{
			
		}
		
	}
	
}